<?php
namespace app\index\controller;
use app\admin\model\Position as PositionModel;
use app\index\model\Shareimg;
use think\Controller;
use think\Db;
use think\Request;

class Position extends Controller
{


    /**
    **首页
    **/
    public function index()
    {
        $companyId  = input('param.company_id','');
        $region     = input('param.region','');
        $jobtype    = input('param.jobtype','');
        $welfare    = input('param.welfare','');
        $title      = input('param.title','');
        $order      = input('param.order','');
        $longitude     = input('param.longitude','');
        $latitude    = input('param.latitude','');

        $where = [];
        if($companyId){
            $where[] = ['company_id','=', $companyId];
        }

        if($region){
            $where[] = ['region_id','=',$region];
        }

        if($jobtype){
            $where[] = ['jobtype','=',$jobtype];
        }

        if($title){
            $where[] = ['title','like',"%$title%"];
        }

        if($welfare){
            $where[] = ['','EXP',Db::raw("FIND_IN_SET('$welfare',welfare)")];
        }

        if($order==1){
            $order = 'salary asc';
        }
        else if($order==2){
            $order = 'salary desc';
        }
        $order = $order?$order:'id desc';
        $count = db('position')->where($where)->count();



        $Page = new \VuePage($count,10);
        $list = db('position')->where($where)->order($order)->limit($Page->getStart(),$Page->getEnd())->select();
        if ($latitude&&$longitude) {

            $distance = " *, (
                    ROUND(
                        6378.138 * 2 * ASIN(
                            SQRT(
                                POW(
                                    SIN(
                                        (
                                            '{$latitude}' * PI() / 180 - latitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                ) + COS('{$latitude}' * PI() / 180) * COS(latitude * PI() / 180) * POW(
                                    SIN(
                                        (
                                            '{$longitude}' * PI() / 180 - longitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                )
                            )
                        ) * 1000
                    )
                ) AS distance";
            $list = db('position')->fieldRaw($distance)
                ->where($where)
                ->order('distance','asc')
                ->order($order)
                ->limit($Page->getStart(),$Page->getEnd())
//                ->fetchSql(true)
                ->select();
//            dump($list); die;
        }

        if($list){
            foreach($list as $k=>$v){
                $list[$k]['signup_num'] = db('signup')->where(['position_id'=>$v['id']])->count();
            }
        }
        $Page->setData($list);
        $return = $Page->indexjson();

        $return['info'] = 'ok';
        $return['status'] = 200;
        $this->_ajaxReturn($return);
    }




    /**
     * 生成二维码
     *
     * @return void
     */
    public function generate($uid, $pid)
    {
        require dirname(dirname(dirname(__DIR__))).'/vendor/phpqrcode/phpqrcode.php';

        //生成的地址
        $url = THEME.'/qrcode/'.$uid.'_'.$pid;
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 10;
        $root = $_SERVER['DOCUMENT_ROOT'];
        $path = 'uploads/down/';
        $filePath = $path.$uid.'_'.md5($url).'.png';
        //判断文件是否存在
        if (!is_dir($root.'/'.$path) ) {
            mkdir($root.'/'.$path, 0777, true);
        }
        //生成二维码图片
        \QRcode::png($url, $filePath, $level, $size);

        return $filePath;
    }



    /**
     * 分享被邀请进入程序
     *
     * @return void
     */
    public function inviteshare($shareId, $userId, $positionId)
    {
        $hunter = db('bounty_hunter')->where('user_id', $shareId)->value('id');
        if($hunter){
            $type = 2;
        }else{
            $type = 1;
        }

        $info = db('share')->where(['type'=>$type, 'share_id'=>$shareId, 'user_id'=>$userId, 'position_id'=>$positionId])->find();
        if($info){
            return true;
        }

        $data['type']     = $type;
        $data['share_id'] = $shareId;
        $data['user_id']  = $userId;
        $data['position_id'] = $positionId;
        $data['status']   = 1;
        $data['ctime']    = time();
        $res = db('share')->insertGetId($data);
        if ($res!==false) {
            return true;
        }else{
            return false;
        }
    }


    /**
     * 详情
     *
     * @return void
     */
    public function details()
    {
        $id = input('param.id',0);
        $userId = input('param.user_id',0);
        $shareId = input('param.share_id', 0);

        if(empty($id)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $position = db('position')->where('id',$id)->find();
        if ($position) {
            $company  = db('company')->where('user_id',$userId)->find();
            $hunterId = db('bounty_hunter')->where('user_id',$userId)->value('id');
            $num = 0;
            if($company){
                $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $endToday   = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                $vuewnumn   = db('position_view')->where([['cid','=',$company['id']], ['ctime','between',"$beginToday,$endToday"]])->count();
                $num = $company['viewnum']-$vuewnumn;
                if($vuewnumn<$company['viewnum']){
                    $data['type']   = 1;
                    $data['cid']    = $company['id'];
                    $data['position_id'] = $id;
                    $data['ctime']  = time();
                    db('position_view')->insertGetId($data);
                }
            }

            $position_view = [];
            if($hunterId){
                $position_view = db('position_view')->where(['type'=>2, 'position_id'=>$id, 'cid'=>$hunterId])->value('id');
            }
            $signup = db('signup')->where(['position_id'=>$id, 'user_id'=>$userId])->value('id');

            $position['is_role'] = $company?3:($hunterId?2:1);
            $position['num'] = $num;
            $position['is_receipt'] = !empty($position_view)?1:0;
            $position['is_signup']  = !empty($signup)?1:0;
            $position['qrcode'] = $this->generate($userId, $id);
            $position['signup_num'] = db('signup')->where(['position_id'=>$id])->count();

            //分享被邀请进入程序
            if($shareId){
                $this->inviteshare($shareId, $userId, $id);
            }
            $this->ajaxReturn($position, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 204);
        }
    }


    /**
     * 报名
     */
    public function signup()
    {
        $post = input('post.');

        if(empty($post['user_id'])){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $user = db('user')->where('id', $post['user_id'])->field('id,nickName,avatarUrl')->find();
        if(empty($user)){
            $this->ajaxReturn(null, '身份验证失败', 201);
        }

        if(empty($post['position_id'])){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $position = db('position')->where('id', $post['position_id'])->field('id,company_id')->find();
        if(empty($position)){
            $this->ajaxReturn(null, '身份验证失败', 201);
        }

        $signup = db('signup')->where(['user_id'=>$post['user_id'], 'position_id'=>$post['position_id']])->field('id,status')->find();
        if(empty($signup) && $signup['status']==1){
            $this->ajaxReturn(null, '已申请该职位', 203);
        }

        if(!empty($post['share_id'])){
            $hunter = db('bounty_hunter')->where(['user_id'=>$post['share_id']])->field('id,status')->find();
            if(empty($hunter)){
                $this->ajaxReturn(null, '无此推广人员', 203);
            }
            $data['type']   = 2;
            $data['hunter_id'] = $hunter['id'];
            $data['share_id']  = $post['share_id'];
        }else{
            $data['type']   = 1;
            $data['company_id'] = $position['company_id'];
        }

        $data['position_id']= $post['position_id'];
        $data['user_id']    = $post['user_id'];
        $data['realname']   = $post['name'];
//        $data['mobile']     = $post['mobile'];
//        $data['sex']        = $post['sex'];
//        $data['age']        = $post['age'];
//      $data['education']   = $post['education'];
//        $data['education']   = $post['education'];

       if(!empty($post['mobile'])) $data['mobile']     = $post['mobile'];
        if(!empty($post['sex'])) $data['sex']        = $post['sex'];
       if(!empty($post['age'])) $data['age']        = $post['age'];
        if(!empty($post['education'])) $data['education']        = $post['education'];

        $data['ctime']      = time();
        $data['status']     = 1;
        // 添加 学历、年龄、

        $res = db('signup')->insertGetId($data);
        if ($res) {
            $this->ajaxReturn($res, '申请成功', 200);
        }else{
            $this->ajaxReturn(null, '申请失败', 200);
        }
    }



    /**
     * 申请职位列表
     */
    public function signuplist()
    {
        $type     = input('get.type');
        $userId   = input('get.user_id');
        $position_id   = input('get.position_id')?input('get.position_id'):0;

        if(empty($type)){
            $this->ajaxReturn(null, '类型错误', 201);
        }
        if(empty($userId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        if($type==1){ //公司
            $field = 'p.id,p.title,p.company_id,p.company_name,p.company_mobile,p.name,p.salary,p.rebate,p.region_name,p.sex,p.agemin,p.agemax,p.experience,p.education,p.welfare
        ,s.user_id,s.realname,s.mobile,s.sex,s.status,s.ctime,s.age';
            $field.= ",u.avatarUrl";
            $join  = [
                ['position p', 'p.id=s.position_id'],
                ['company c', 'c.id=s.company_id'],
                ['user u', 'u.id=s.user_id'],
            ];
            $where['c.user_id'] = $userId;
            $where['s.type'] = $type;
            $where['s.position_id'] = $position_id;
        }
        else if($type==2){ // 猎人
            $where['b.user_id']  = $userId;
            $where['s.type'] = $type;
            $where['s.position_id'] = $position_id;

            $join  = [
                ['bounty_hunter b', 'b.id=s.hunter_id'],
                ['position p', 'p.id=s.position_id'],
                ['user u', 'u.id=s.user_id'],
            ];
            $field = 'p.*,s.user_id,s.realname,s.mobile,s.sex,s.status,s.ctime,s.age';
            $field.= ",u.avatarUrl";
        }
        elseif($type==3){
            $field = 'p.id,p.title,p.company_name,p.company_mobile,p.name,p.salary,p.rebate,p.region_name,p.sex,p.agemin,p.agemax,p.experience,p.education,p.welfare
        ,s.user_id,s.realname,s.mobile,s.sex,s.status,s.ctime,s.age';
            $field.= ",u.avatarUrl";
            $join  = [
                ['position p', 'p.id=s.position_id'],
                ['user u', 'u.id=s.user_id'],
            ];
            $where['s.user_id']  = $userId;

        }

        $count = db('signup')->alias('s')
            ->join($join)
            ->where($where)
            ->count();

        $Page = new \VuePage($count,10);
        $list = db('signup')->alias('s')->join($join)
            ->where($where)->order('s.id desc')
            ->limit($Page->getStart(),
                $Page->getEnd())->field($field)
            ->select();
        $Page->setData($list);
        $return = $Page->indexjson();

        $return['info'] = 'ok';
        $return['status'] = 200;
        $this->_ajaxReturn($return);
    }



    /**
     *
     * 猎人申请接单
     * @param Type $var
     * @return void
     */
    public function receipt()
    {
        $positionId = input('post.position_id');
        $userId     = input('post.user_id');
        $is_cancel  = input('post.is_cancel');
        if(empty($positionId) || empty($userId)){
            $this->ajaxReturn([], '参数为空', 201);
        }

        $hunter = db('bounty_hunter')->where(['user_id'=>$userId ])->find();
        if(empty($hunter)){
            $this->ajaxReturn([], '无此赏金猎人', 201);
        }
        $view = db('position_view')->where(['type'=>2, 'cid'=>$hunter['id'], 'position_id'=>$positionId ])->find();

        if($is_cancel){
            if(empty($view)){
                $this->ajaxReturn([], '未申请', 201);
            }
            //删除数据
            $res = db('position_view')->where(id, $view['id'])->delete();
        }else{
            if($view){
                $this->ajaxReturn([], '已申请', 201);
            }
            //添加数据
            $res = db('position_view')->insertGetId(['type'=>2, 'cid'=>$hunter['id'], 'position_id'=>$positionId,'ctime'=>time() ]);
        }

        if($res!==false){
            $this->ajaxReturn($res, '接单成功', 200);
        }else{
            $this->ajaxReturn(null, '接单失败', 204);
        }

    }




    /**
     * 分享
     *
     * @return void
     */
    public function share()
    {
        $type = input('get.type');
        $cid  = input('get.cid');
        $positionId  = input('get.position_id');
        if(empty($type) || empty($cid) || empty($positionId)){
            $this->ajaxReturn([], '参数为空', 201);
        }

        if($type!=3 || $type!=4){
            $this->ajaxReturn([], '非分享操作', 201);
        }

        if($type==3){
            $b = db('bounty_hunter')->where('id', $cid)->find();
            if(empty($b)){
                $this->ajaxReturn([], '无此赏金猎人', 201);
            }
        }

        if($type==4){
            $b = db('user')->where('id', $cid)->find();
            if(empty($b)){
                $this->ajaxReturn([], '无此用户', 201);
            }
        }

        $data['type']   = $type;
        $data['cid']    = $cid;
        $data['position_id'] = $positionId;
        $data['ctime']  = time();
        $res = db('position_view')->insertGetId($data);

        if ($res){
            $this->ajaxReturn($res, 'ok', 200);
        }else{
            $this->ajaxReturn([], '数据为空', 200);
        }
    }


    /**
     * 查询职位-分享-申请
     *
     * @return void
     */
    public function positionview()
    {
        $type = input('get.type');
        $userId  = input('get.user_id');
        $pageno   = input('get.pageno', 0);

        if(empty($type)){
            $this->ajaxReturn([], '无参数配置', 201);
        }

        if(empty($userId)){
            $this->ajaxReturn([], '参数错误', 201);
        }

        if($type==1){
            $cid = db('company')->where('user_id', $userId)->value('id');
        }
        else if($type==2 || $type==3){
            $cid = db('bounty_hunter')->where('user_id', $userId)->value('id');
        }else{
            $cid = $userId;
        }

        $join = [['position p', 'p.id=v.position_id']];
        $field = 'p.id,p.title,p.company_name,p.company_mobile,p.name,p.salary,p.rebate,p.region_name,p.sex,p.agemin,p.agemax,p.experience,p.education,p.welfare,v.ctime';
        $where['v.type'] = $type;
        $where['v.cid']  = $cid;
        $count = db('position_view')->alias('v')->join($join)->where($where)->count();
        $Page = new \VuePage($count,10);
        $list = db('position_view')->alias('v')->join($join)->where($where)->order('v.id desc')->limit($Page->getStart(),$Page->getEnd())->field($field)->select();
        $Page->setData($list);
        $return = $Page->indexjson();

        $return['info'] = 'ok';
        $return['status'] = 200;
        $this->_ajaxReturn($return);
    }



    # 获取推广码
    public function getSharePic(Request $request)
    {
        $position_id = $request->get('position_id');
        $user_id = $request->get('user_id');

        $positonModel = PositionModel::find($position_id);
        if(!$positonModel) {
            return returnData([],'数据不存在','fail');
        }
       $data = (new Shareimg())->getmakepic($positonModel, $user_id);

        return returnData($data);
    }






}
